package gui.clientes;

import bin.Armazem;
import bin.clientes.Cliente;
import bin.clientes.Telefone;
import bin.exc.ECadastroInvalido;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class PainelCadastroClientes extends javax.swing.JPanel {

    //Atributos
    private Armazem armazem;
    private ArrayList<Telefone> listaTelefones;
    private Cliente clienteEdicao;
    
    //Construtor
    public PainelCadastroClientes(Armazem armazem) {
        initComponents();
        
        this.armazem = armazem;
        this.listaTelefones = new ArrayList<Telefone>();
    }

    //Setar foco no campo "Nome" (Componente primário para foco)
    public void focoCompPadrao()
    {
        this.txtNome.requestFocus();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tipoCliente = new javax.swing.ButtonGroup();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txtEndereco = new javax.swing.JTextField();
        txtNome = new javax.swing.JTextField();
        txtCidade = new javax.swing.JTextField();
        txtPais = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbTelefone = new javax.swing.JTable();
        txtEstado = new javax.swing.JFormattedTextField();
        txtCpf = new javax.swing.JFormattedTextField();
        txtCnpj = new javax.swing.JFormattedTextField();
        slFisico = new javax.swing.JRadioButton();
        slJuridico = new javax.swing.JRadioButton();
        txtRg = new javax.swing.JTextField();
        cmbTelefone = new javax.swing.JComboBox();
        txtTelefone = new javax.swing.JFormattedTextField();
        btAddTelefone = new javax.swing.JButton();
        lbIconClientes = new javax.swing.JLabel();
        btAddTelefone1 = new javax.swing.JButton();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        jLabel2.setText("Nome:");

        jLabel3.setText("Endereço:");

        jLabel4.setText("Cpf:");

        jLabel5.setText("Telefones:");

        jLabel1.setText("Cidade:");

        jLabel6.setText("Estado:");

        jLabel7.setText("País:");

        jLabel8.setText("Cnpj:");

        jLabel9.setText("Rg:");

        tbTelefone.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo", "Telefone"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbTelefone.setShowHorizontalLines(false);
        jScrollPane2.setViewportView(tbTelefone);

        try {
            txtEstado.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("AA")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        try {
            txtCpf.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        txtCnpj.setEditable(false);
        try {
            txtCnpj.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        slFisico.setBackground(new java.awt.Color(255, 255, 255));
        tipoCliente.add(slFisico);
        slFisico.setSelected(true);
        slFisico.setText("Físico");
        slFisico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                slFisicoActionPerformed(evt);
            }
        });

        slJuridico.setBackground(new java.awt.Color(255, 255, 255));
        tipoCliente.add(slJuridico);
        slJuridico.setText("Jurídico");
        slJuridico.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                slJuridicoActionPerformed(evt);
            }
        });

        cmbTelefone.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Residencial", "Celular", "Empresarial", "Outro" }));

        try {
            txtTelefone.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        btAddTelefone.setBackground(new java.awt.Color(255, 255, 255));
        btAddTelefone.setText("Add");
        btAddTelefone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddTelefoneActionPerformed(evt);
            }
        });

        lbIconClientes.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lbIconClientes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/cadastroCliente.png"))); // NOI18N

        btAddTelefone1.setBackground(new java.awt.Color(255, 255, 255));
        btAddTelefone1.setText("Remover");
        btAddTelefone1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddTelefone1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 549, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 10, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel8))
                                .addGap(28, 28, 28)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txtNome)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(17, 17, 17)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(slJuridico)
                                            .addComponent(slFisico))
                                        .addGap(0, 0, Short.MAX_VALUE))))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cmbTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(lbIconClientes))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(btAddTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(btAddTelefone1))
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel4))
                                .addGap(22, 22, 22)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtCidade)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel7))
                                    .addComponent(txtCpf))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(txtPais, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel9)
                                        .addGap(18, 18, 18)
                                        .addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(txtPais, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(slFisico)
                    .addComponent(jLabel9)
                    .addComponent(txtRg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtCnpj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(slJuridico))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btAddTelefone1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(txtTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btAddTelefone)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbIconClientes))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    //Tipo do cliente (Fisico ou Juridico). Setar Campos para CPF ou CNPJ
    private void slFisicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_slFisicoActionPerformed
        if(this.slFisico.isSelected())
        {
            this.txtCpf.setEditable(true);
            this.txtCnpj.setEditable(false);
            this.txtCnpj.setText("");
            return;
        }
        this.txtCpf.setEditable(false);
    }//GEN-LAST:event_slFisicoActionPerformed
    private void slJuridicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_slJuridicoActionPerformed
        if(this.slJuridico.isSelected())
        {
            this.txtCnpj.setEditable(true);
            this.txtCpf.setEditable(false);
            this.txtCpf.setText("");
            return;
        }
        this.txtCnpj.setEditable(false);
    }//GEN-LAST:event_slJuridicoActionPerformed

    //Adicionar telefone na lista
    private void btAddTelefoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddTelefoneActionPerformed
        DefaultTableModel dtm = (DefaultTableModel)this.tbTelefone.getModel();
        
        String tipo = this.cmbTelefone.getSelectedItem() + "";
        String telefone = this.txtTelefone.getText();
        
        //Validar se número já existe
        for(Telefone t : this.listaTelefones)
        {
            if(t.getTelefone().equals(telefone))
            {
                JOptionPane.showMessageDialog(this, "Número já adicionado.","Erro",JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        this.listaTelefones.add(new Telefone(tipo, telefone));
        String[] linha = new String[]{tipo, telefone};
        dtm.addRow(linha);
        
        this.txtTelefone.setText("");
    }//GEN-LAST:event_btAddTelefoneActionPerformed

    //Remover telefone da lista
    private void btAddTelefone1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddTelefone1ActionPerformed
        
        if(this.tbTelefone.getSelectedRow() != -1)
        {
            DefaultTableModel dtm = (DefaultTableModel)this.tbTelefone.getModel();
        
            //Deletar telefone da lista de telefones
            String telefone = dtm.getValueAt(this.tbTelefone.getSelectedRow(), 1) + "";
            for(Telefone t : this.listaTelefones)
            {
                if(t.getTelefone().equals(telefone))
                {
                    this.listaTelefones.remove(t);
                    break;
                }
            }
            dtm.removeRow(this.tbTelefone.getSelectedRow());
        }
        else
        {
            JOptionPane.showMessageDialog(this, "Deve estar selecionada uma linha da tabela para ser removida.","Info",JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btAddTelefone1ActionPerformed

    //Jogar informações do cliente cujo sofrerá edição nos campos do painel
    public void editarCliente(Cliente c)
    {
        this.clienteEdicao = c;
        
        this.txtNome.setText(c.getNome());
        this.txtEndereco.setText(c.getEndereco());
        if(c.isFisico())
        {
            this.slFisico.setSelected(true);
            this.txtCpf.setEditable(true);
            this.txtCnpj.setEditable(false);
        }
        else
        {
            this.slJuridico.setSelected(true);
            this.txtCnpj.setEditable(true);
            this.txtCpf.setEditable(false);
        }
        this.txtCpf.setText(c.getCpf());
        this.txtCnpj.setText(c.getCnpj());
        this.txtCidade.setText(c.getCidade());
        this.txtEstado.setText(c.getEstado());
        this.txtPais.setText(c.getPais());
        this.txtRg.setText(c.getRg());
        
        this.listaTelefones = new ArrayList<Telefone>();
        DefaultTableModel dtm = (DefaultTableModel)this.tbTelefone.getModel();
        for(Telefone t : c.getListaTelefones())
        {
            dtm.addRow(new Object[]{t.getTipo(),t.getTelefone()});
            this.listaTelefones.add(new Telefone(t.getTipo(),t.getTelefone()));
        }
    }
    
    //Concluir Edição do cliente.
    public void concluirEdicao() throws ECadastroInvalido
    {
        this.clienteEdicao.setNome(this.txtNome.getText());
        this.clienteEdicao.setEndereco(this.txtEndereco.getText());
        this.clienteEdicao.setCpf(this.txtCpf.getText());
        this.clienteEdicao.setCnpj(this.txtCnpj.getText());
        this.clienteEdicao.setCidade(this.txtCidade.getText());
        this.clienteEdicao.setEstado(this.txtEstado.getText());
        this.clienteEdicao.setPais(this.txtPais.getText());
        this.clienteEdicao.setRg(this.txtRg.getText());
        this.clienteEdicao.setFisico(this.slFisico.isSelected());
        this.clienteEdicao.setListaTelefones(this.listaTelefones);
    }
    
    //Concluir Cadastro do cliente. Retorna exceção se os campos não estiverem preenchidos
    public void concluirCadastro() throws ECadastroInvalido
    {
        //Definir novo ID
        int id = this.armazem.getListaClientes().size()+1;
        String nome = this.txtNome.getText();
        String endereco = this.txtEndereco.getText();
        String cpf = this.txtCpf.getText();
        String cnpj = this.txtCnpj.getText();
        String cidade = this.txtCidade.getText();
        String estado = this.txtEstado.getText();
        String pais = this.txtPais.getText();
        String rg = this.txtRg.getText();
        boolean fisico = this.slFisico.isSelected();
        ArrayList<Telefone> novaListaTelefones = listaTelefones;
        
        Cliente cliente = new Cliente(id,nome,endereco,cpf,cnpj,cidade,estado,pais,rg,fisico,novaListaTelefones);
        this.armazem.getListaClientes().add(cliente);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAddTelefone;
    private javax.swing.JButton btAddTelefone1;
    private javax.swing.JComboBox cmbTelefone;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbIconClientes;
    private javax.swing.JRadioButton slFisico;
    private javax.swing.JRadioButton slJuridico;
    private javax.swing.JTable tbTelefone;
    private javax.swing.ButtonGroup tipoCliente;
    private javax.swing.JTextField txtCidade;
    private javax.swing.JFormattedTextField txtCnpj;
    private javax.swing.JFormattedTextField txtCpf;
    private javax.swing.JTextField txtEndereco;
    private javax.swing.JFormattedTextField txtEstado;
    private javax.swing.JTextField txtNome;
    private javax.swing.JTextField txtPais;
    private javax.swing.JTextField txtRg;
    private javax.swing.JFormattedTextField txtTelefone;
    // End of variables declaration//GEN-END:variables
}
